package com.sdyc.ndmp.cls.server;

import akka.actor.ActorSystem;
import com.typesafe.config.ConfigFactory;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

/**
 * <pre>
 * Created with IntelliJ IDEA.
 * User: zachary
 * Date: 2015/11/19
 * Time: 11:35
 * </pre>
 *
 * @author zachary
 */
public class ActorServer implements InitializingBean, DisposableBean, Runnable {


    protected ActorSystem tx = null;



    protected final Thread clsAkkaHandlerThread = new Thread(this);


    protected boolean daemon = false;


    protected static Log LOG = LogFactory.getLog(ActorServer.class);



    public ActorServer() {
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        LOG.info("starting akka server.");
        clsAkkaHandlerThread.setDaemon(true);
        clsAkkaHandlerThread.setName("cls-akka-server-thread");
        clsAkkaHandlerThread.start();

        if(daemon) {
            clsAkkaHandlerThread.join();
        }

        LOG.info("started akka server.");
    }



    @Override
    public void run() {
        tx = ActorSystem.create("CLSAkkaMaster",
                ConfigFactory.load("server"));
    }


    @Override
    public void destroy() throws Exception {
        LOG.info("stoping akka server.");
        if(tx != null) {
            try {
                tx.shutdown();
            } catch (Exception e) {
                LOG.error(ExceptionUtils.getFullStackTrace(e));
            }
        }


        if(clsAkkaHandlerThread.isAlive()) {
            try {
                clsAkkaHandlerThread.interrupt();
                clsAkkaHandlerThread.join();
            } catch (Exception e) {
                LOG.error(ExceptionUtils.getFullStackTrace(e));
            }
        }
        LOG.info("stoped akka server.");
    }


    public boolean isDaemon() {
        return daemon;
    }

    public void setDaemon(boolean daemon) {
        this.daemon = daemon;
    }

    public static void main(String[] args) throws Exception {
        ActorServer server = new ActorServer();
        server.setDaemon(true);
        server.afterPropertiesSet();
    }

}
